package com.gl.emms.whale.ui;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.SeriesSelection;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

import com.gl.emms.client.android.EMMSPushManager;
import com.gl.emms.nio.mutual.ReplyBody;
import com.gl.emms.whale.R;
import com.gl.emms.whale.app.MyApplication;
import com.gl.emms.whale.app.WhaleMonitorActivity;
import com.gl.emms.whale.util.TimeTools;

/**能耗分析界面类
 * @author ganlinux
 *
 */
@SuppressLint("SimpleDateFormat")
public class EnergyAnalysisActivity extends WhaleMonitorActivity implements
OnClickListener{
	//存储数据传来的分析数据
	private HashMap<String, String> data =new HashMap<String, String>();
	
	private Button titleBackBtn;//返回按钮
	private Button dayDataButton;;//
	private Button monthDataButton;

	private LinearLayout layout; //用于绑定图表控件。
	private String[] titles = new String[] { "上月能量数据", "本月能量数据", "去年此月能量数据"};
	
	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd-HH");//小写的mm表示的是分钟  时间格式化
	
	//时间列表
	List<Date[]> timeList = new ArrayList<Date[]>();
	//数据列表
	List<double[]> valueList = new ArrayList<double[]>();
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		setContentView(R.layout.activity_energyanalysis);
		//初始化控件
		initViews();

		/*
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH");//小写的mm表示的是分钟  
		List<Date[]> time = new ArrayList<Date[]>();
		for (int i = 0; i < titles.length; i++) {
			try {
				time.add(new Date[] { sdf.parse("2014-10-01 10"), sdf.parse("2014-10-01 11"), sdf.parse("2014-10-01 12"), sdf.parse("2014-10-01 13"), sdf.parse("2014-10-01 14"), sdf.parse("2014-10-01 15"), sdf.parse("2014-10-01 16"), sdf.parse("2014-10-01 17"), sdf.parse("2014-10-01 18"), sdf.parse("2014-10-01 19"), sdf.parse("2014-10-01 20"), sdf.parse("2014-10-01 21") });
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		List<double[]> values = new ArrayList<double[]>();
		values.add(new double[] { 12.3, 12.5, 13.8, 16.8, 20.4, 24.4, 26.4, 26.1, 23.6, 20.3, 17.2, 13.9 });
		values.add(new double[] { 10, 10, 12, 15, 20, 24, 26, 26, 23, 18, 14, 11 });
		values.add(new double[] { 5, 5.3, 8, 12, 17, 22, 24.2, 24, 19, 15, 9, 6 });
		int[] colors = new int[] { Color.BLUE, Color.GREEN, Color.CYAN};
		PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE, PointStyle.DIAMOND, PointStyle.TRIANGLE};
		XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
		int length = renderer.getSeriesRendererCount();
		for (int i = 0; i < length; i++) {
			((XYSeriesRenderer) renderer.getSeriesRendererAt(i)).setFillPoints(true);
		}
		setChartSettings(renderer, "能耗分析", "月份", "能量数据", 1, 5, 0, 40, Color.LTGRAY, Color.LTGRAY);
		//renderer.setXLabels(12);
		renderer.setYLabels(10);
		renderer.setShowGrid(true);
		renderer.setXLabelsAlign(Align.RIGHT);
		renderer.setYLabelsAlign(Align.RIGHT);

		View view = ChartFactory.getTimeChartView(this, buildDateDataset(titles, time, values), renderer,"yy-MM-dd HH");
		//view.setBackgroundColor(Color.BLACK);
		view.setOnClickListener(gOCL);
		layout.addView(view,new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
		 */
		
		//获取一周内数据
		Calendar endCalendar = Calendar.getInstance();  
		int endYear = endCalendar.get(Calendar.YEAR);  
		int endMonth = endCalendar.get(Calendar.MONTH)+1;  
		int endDay = endCalendar.get(Calendar.DAY_OF_MONTH);  
		int endHour = endCalendar.get(Calendar.HOUR_OF_DAY); 

		Calendar startCalendar = TimeTools.getDateBefore(endCalendar,7);
		int startYear = startCalendar.get(Calendar.YEAR);  
		int startMonth = startCalendar.get(Calendar.MONTH)+1;  
		int startDay = startCalendar.get(Calendar.DAY_OF_MONTH);  
		int startHour = startCalendar.get(Calendar.HOUR_OF_DAY);  

		String startTime = String.format("%d-%d-%d %d", startYear,startMonth,startDay,startHour);
		String endTime = String.format("%d-%d-%d %d", endYear,endMonth,endDay,endHour);

		showProgressDialog("提示", "正在更新数据，请稍后......");
		String roomStr = MyApplication.getUserData().getMainroom(); 
		//发送能量表数据请求
		EMMSPushManager.setNlbDataRequest(this,MyApplication.getUserData().getIdIP(),roomStr,startTime, endTime);
	}
	/**
	 * 初始化控件
	 */
	public void initViews() {
		titleBackBtn = (Button)findViewById(R.id.TitleBackBtn); 
		titleBackBtn.setOnClickListener(this);
		dayDataButton = (Button)findViewById(R.id.day_btn); 
		dayDataButton.setOnClickListener(this);
		monthDataButton = (Button)findViewById(R.id.month_btn); 
		monthDataButton.setOnClickListener(this);
		layout = (LinearLayout)findViewById(R.id.chart);
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.button1:

			break;
		case R.id.button2:

			break;
		case R.id.TitleBackBtn:
			//用intent启动拨打电话  
			KeyEvent newEvent = new KeyEvent(KeyEvent.ACTION_DOWN,  KeyEvent.KEYCODE_BACK);
			finish();
			break;
		default:
			break;
		}
	}
	/**创建renderer
	 * @param colors
	 * @param styles
	 * @return
	 */
	private XYMultipleSeriesRenderer buildRenderer(int[] colors, PointStyle[] styles) {
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		setRenderer(renderer, colors, styles);
		return renderer;
	}

	/**设置renderer
	 * @param renderer
	 * @param colors
	 * @param styles
	 */
	private void setRenderer(XYMultipleSeriesRenderer renderer, int[] colors, PointStyle[] styles) {
		renderer.setClickEnabled(true); //是否可以点击
		renderer.setMarginsColor(Color.argb(0x00, 0x01, 0x01, 0x01));
		renderer.setApplyBackgroundColor(true);//设置是否显示背景色  
		renderer.setBackgroundColor(Color.argb(100, 50, 50, 50));//设置背景色  

		renderer.setAxisTitleTextSize(20); //设置轴标题文字的大小  
		renderer.setChartTitleTextSize(30);//?设置整个图表标题文字大小  
		renderer.setLabelsTextSize(25);//设置刻度显示文字的大小(XY轴都会被设置)  
		renderer.setLegendTextSize(20);//图例文字大小  
		renderer.setMargins(new int[] { 50, 70, 50, 40 });//设置图表的外边框(上/左/下/右) 
		renderer.setZoomButtonsVisible(true);//是否显示放大缩小按钮  
		//renderer.setPanLimits(new double[] { 1, 12, 0, 40 });
		//renderer.setZoomLimits(new double[] { 1, 12, 0, 40 });
		renderer.setPointSize(5);//设置点的大小(图上显示的点的大小和图例中点的大小都会被设置)


		int length = colors.length;
		for (int i = 0; i < length; i++) {
			XYSeriesRenderer r = new XYSeriesRenderer();
			r.setColor(colors[i]);
			r.setPointStyle(styles[i]);
			r.setDisplayChartValues(true);
			r.setChartValuesTextAlign(Align.RIGHT);
			r.setChartValuesTextSize(20);
			renderer.addSeriesRenderer(r);
		}
	}
	//点击事件
	OnClickListener gOCL = new OnClickListener() {

		@Override
		public void onClick(View v) { 
			GraphicalView gv = (GraphicalView) v;
			//将view转换为可以监听的GraphicalView
			SeriesSelection ss = gv.getCurrentSeriesAndPoint();
			//获得被点击的系列和点
			if (ss == null) return ;
			double[] point = new double[]{ss.getXValue(),ss.getValue()};
			//获得当前被点击点的X位置和Y数值
			//获得当前被点击点的坐标位置
			showToask("时间："+point[0]+",数据："+point[1]+"\n");
		}
	};
	/**设置图标参数
	 * @param renderer
	 * @param title
	 * @param xTitle
	 * @param yTitle
	 * @param xMin
	 * @param xMax
	 * @param yMin
	 * @param yMax
	 * @param axesColor
	 * @param labelsColor
	 */
	private void setChartSettings(XYMultipleSeriesRenderer renderer, String title, String xTitle, String yTitle, double xMin, double xMax, double yMin, double yMax, int axesColor, int labelsColor) {
		Calendar endCalendar = Calendar.getInstance();  
		int endYear = endCalendar.get(Calendar.YEAR);  
		int endMonth = endCalendar.get(Calendar.MONTH)+1;  
		int endDay = endCalendar.get(Calendar.DAY_OF_MONTH);  
		int endHour = endCalendar.get(Calendar.HOUR_OF_DAY); 

		Calendar startCalendar = TimeTools.getDateBefore(endCalendar,7);
		int startYear = startCalendar.get(Calendar.YEAR);  
		int startMonth = startCalendar.get(Calendar.MONTH)+1;  
		int startDay = startCalendar.get(Calendar.DAY_OF_MONTH);  
		int startHour = startCalendar.get(Calendar.HOUR_OF_DAY);  
		String startTime = String.format("%d-%d-%d-%d", startYear,startMonth,startDay,startHour);
		String endTime = String.format("%d-%d-%d-%d", endYear,endMonth,endDay,endHour);
		
		
		renderer.setChartTitle(title);
		renderer.setXTitle(xTitle);
		renderer.setYTitle(yTitle);

		try {
			renderer.setXAxisMin(sdf.parse(startTime).getTime());
			renderer.setXAxisMax(sdf.parse(endTime).getTime());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


		renderer.setYAxisMin(yMin);
		renderer.setYAxisMax(yMax);
		renderer.setAxesColor(axesColor);
		renderer.setLabelsColor(labelsColor);
	}
	/*
	private XYMultipleSeriesDataset buildDataset(String[] titles, List<double[]> xValues, List<double[]> yValues) {
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
		addXYSeries(dataset, titles, xValues, yValues, 0);
		return dataset;
	}
	 */
	/**绑定数据
	 * @param titles
	 * @param xValues
	 * @param yValues
	 * @return
	 */
	protected XYMultipleSeriesDataset buildDateDataset(String[] titles, List<Date[]> xValues,
			List<double[]> yValues) {
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
		int length = titles.length;
		for (int i = 0; i < length; i++) {
			TimeSeries series = new TimeSeries(titles[i]);
			Date[] xV = xValues.get(i);      //画TimeChart横坐标需要为Date数据类型
			double[] yV = yValues.get(i);
			int seriesLength = xV.length;
			for (int k = 0; k < seriesLength; k++) {
				series.add(xV[k], yV[k]);
			}
			dataset.addSeries(series);
		}
		return dataset;
	}

	@Override
	public void onReplyReceived(final ReplyBody reply) {
		if (reply.getType().equals("nlbdata_response")) {
			//DialogFactory.ToastDialog(EnergyAnalysisActivity.this, "数据更新","成功");
			data = reply.getData();
			//  将HASHMAP中的数据排序-------------------------------------------
			new MyThread().start();
		}
	}
	private Handler mHandler = new Handler() {  
		@Override  
		public void handleMessage(Message msg) {  
			if (msg.what == 0x06) {  
				hideProgressDialog();
				showChart();
			}  
		}  
	};
	public class MyThread extends Thread {  
		public void run() {  
			//while (!Thread.currentThread().isInterrupted()) 
			{  
				Date[] times = new Date[data.size()-4];
				double[] dates = new double[data.size()-4];
				int i=0;
				
				Object[]   key   =     data.keySet().toArray();  
		        Arrays.sort(key); 
		        for (int j = 0; j < key.length-4; j++) {
		        	//Map.Entry entry = (Map.Entry) iter.next();
		        	String timeStr = key[j].toString().substring(1, key[j].toString().length());
		        	//String timeStr = entry.getKey().toString().substring(1, entry.getKey().toString().length());
					try {
						//convertdata.put(sdf.parse(timeStr), Double.parseDouble(entry.getValue().toString()));
						times[i] = sdf.parse(timeStr);
						dates[i] = Double.valueOf(data.get(key[j]));
						i++;

					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
		        /* 
				while (iter.hasNext()) {

					Map.Entry entry = (Map.Entry) iter.next();
					//EnergyEntity entity = new EnergyEntity((Date)entry.getKey(),entry.getValue().toString());
					//EnergyAnalysisDB energyAnalysisDB = new EnergyAnalysisDB(EnergyAnalysisActivity.this);
					//energyAnalysisDB.saveRecord(entity, "0001");
					if ((entry.getKey().toString().equals("endtime"))||(entry.getKey().toString().equals("starttime"))||(entry.getKey().toString().equals("metertype"))||(entry.getKey().toString().equals("room"))) {

					}else
					{
						String timeStr = entry.getKey().toString().substring(1, entry.getKey().toString().length());

						try {
							//convertdata.put(sdf.parse(timeStr), Double.parseDouble(entry.getValue().toString()));
							times[i] = sdf.parse(timeStr);
							dates[i] = Double.valueOf(entry.getValue().toString());
							i++;

						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}



				}*/
				timeList.add(times);
				timeList.add(times);
				timeList.add(times);

				valueList.add(dates);
				valueList.add(dates);
				valueList.add(dates);


				Message msg = new Message();  
				msg.what = 0x06;  
				mHandler.sendMessage(msg);  


			}  
		}  
	}
	private void showChart() {
		prepareData();
		showData();

	}
	private void prepareData() {

		for (int i = 0; i < titles.length; i++) {
			/*
			try {

				timeList.add(new Date[] { sdf.parse("2014-10-01-10"), sdf.parse("2014-10-01-11"), sdf.parse("2014-10-01-12"), sdf.parse("2014-10-01-13"), sdf.parse("2014-10-01-14"), sdf.parse("2014-10-01-15"), sdf.parse("2014-10-01-16"), sdf.parse("2014-10-01-17"), sdf.parse("2014-10-01-18"), sdf.parse("2014-10-01-19"), sdf.parse("2014-10-01-20"), sdf.parse("2014-10-01-21") });
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			valueList.add(new double[] { 12.3, 12.5, 13.8, 16.8, 20.4, 24.4, 26.4, 26.1, 23.6, 20.3, 17.2, 13.9 });
			 */
			//time.addAll(convertdata.keySet().);
			//time.addAll();
			//values.addAll(convertdata.values());
		}

		//valueList.add(new double[] { 12.3, 12.5, 13.8, 16.8, 20.4, 24.4, 26.4, 26.1, 23.6, 20.3, 17.2, 13.9 });
		//valueList.add(new double[] { 10, 10, 12, 15, 20, 24, 26, 26, 23, 18, 14, 11 });
		//valueList.add(new double[] { 5, 5.3, 8, 12, 17, 22, 24.2, 24, 19, 15, 9, 6 });
	}
	private void showData() {
		int[] colors = new int[] { Color.BLUE, Color.GREEN, Color.CYAN};
		PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE, PointStyle.DIAMOND, PointStyle.TRIANGLE};
		XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
		int length = renderer.getSeriesRendererCount();
		for (int i = 0; i < length; i++) {
			((XYSeriesRenderer) renderer.getSeriesRendererAt(i)).setFillPoints(true);
		}
		setChartSettings(renderer, "能耗分析", "月份", "能量数据", 1, 5, 0, 20000, Color.LTGRAY, Color.LTGRAY);
		//renderer.setXLabels(12);
		renderer.setYLabels(10);
		renderer.setShowGrid(true);
		renderer.setXLabelsAlign(Align.RIGHT);
		renderer.setYLabelsAlign(Align.RIGHT);

		View view = ChartFactory.getTimeChartView(this, buildDateDataset(titles, timeList, valueList), renderer,"yy-MM-dd HH");
		//view.setBackgroundColor(Color.BLACK);
		view.setOnClickListener(gOCL);
		layout.addView(view,new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
	}
	
	@Override
	public void onUserCancel()
	{
		super.onUserCancel();
		finish();
	}
}
